package com.chatgpt.api.interceptor;

import com.chatgpt.api.controller.BaseController;
import com.chatgpt.api.exception.UnAuthorizedException;
import com.chatgpt.api.service.UserService;
import com.chatgpt.api.service.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 请求拦截器，判断用户是否授权
@Component
public class SessionInterceptor implements HandlerInterceptor {
    private final UserService userService;

    public SessionInterceptor(UserService userService) {
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String token = request.getHeader("Authorization");
        if (StringUtils.isBlank(token)) {
            throw new UnAuthorizedException("You should put Authorization in request headers");
        }

        User user = userService.getUserFromToken(token);

        if (user == null) {
            throw new UnAuthorizedException();
        }

        // 注入用户信息
        request.setAttribute(BaseController.LOGIN_USER, user);

        return true;
    }
}
